import { bindable, containerless } from 'aurelia-framework';

@containerless
export class EmTaskList {

    @bindable value;

    valueChanged(newValue, oldValue) {

    }

    page = 0;

    /**
     * 构造函数
     */
    constructor() {
        this.subscribe = ea.subscribe(nsCons.EVENT_TASK_SEARCH, (payload) => {
            this.search = payload;
            this.page = 0;
            this._search();
        });
    }

    /**
     * 当数据绑定引擎从视图解除绑定时被调用
     */
    unbind() {
        this.subscribe.dispose();
    }

    bind(bindingCtx, overrideCtx) {
        // this._search();
    }

    _search() {

        let searchParams = {
            page: this.page,
            sort: 'projectTaskId,desc',
            projects: '',
            types: '',
            states: '',
            operators: '',
        };

        if (this.search) {
            searchParams.projects = _.chain(this.search.projects).map('id').join().value();
            searchParams.types = _.chain(this.search.types).map('id').join().value();
            searchParams.states = _.chain(this.search.states).map('id').join().value();
            searchParams.operators = _.chain(this.search.operators).map('id').join().value();
        }

        this.searchAjax = $.get(`/admin/task/search`, searchParams, (data) => {
            if (data.success) {
                this.taskPage = data.data;
                if (data.data.content.length > 0) {
                    ea.publish(nsCons.EVENT_TASK_SELECTED_CHANGED, data.data.content[0]);
                }
            } else {
                toastr.error(data.data);
            }
        });
    }

    refreshHandler() {
        this._search();
    }

    switchPageHandler(page) {
        this.page = page;
        this._search();
    }
}
